<?php

namespace Trois\MainServerRegister\Registers;

use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\EasySwoole\ServerManager;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\FileWatcher\FileWatcher;
use EasySwoole\FileWatcher\WatchRule;
use EasySwoole\EasySwoole\Core;
use Trois\Design\Observer\IObserver;

class FileWatcherRegister extends BaseRegister implements IObserver
{
    use Singleton;

    private array $paths; // 监控目录

    private function __construct(EventRegister $register)
    {
        $this->paths = [
            'Trois',
            'App',
        ];

        parent::__construct($register);

    }

    public function update()
    {
        if (Core::getInstance()->runMode() === 'dev') {

            $watcher = new FileWatcher();

            foreach ($this->paths as $path) {
                $watcher->addRule(new WatchRule(EASYSWOOLE_ROOT . "/" . $path));
            }

            $watcher->setOnChange(function () {
                Logger::getInstance()->info('file change ' . date('H:i:s'));
                ServerManager::getInstance()->getSwooleServer()->reload();
            });

            $watcher->attachServer(ServerManager::getInstance()->getSwooleServer());

        }
    }

}